<?php

namespace App\Http\Controllers\Api\SmallApp\Login;

use App\Http\Controllers\Common\ApiController;
use App\Models\User\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Redis;

class LoginController extends ApiController {

    public function accountLogin(Request $request) {
        $phone = $request->input('phone');
        $password = $request->input('password');

        $this->validate($request, [
            'phone'=>'required',
            'password'=>'required',
        ]);

        $user = User::where(['phone'=>$phone,'password'=>md5($password)])->first();
        if(empty($user)) return responseFail('未查到有效用户或请先去注册！');
        else{
            $user->token = createNewToken($user->id);
            return responseSuccess($user->toArray());
        }
    }

    public function phoneLogin(Request $request) {
        $phone = $request->input('phone');
        $verify_code = $request->input('verify_code');
        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|integer',
        ]);

        if(env('APP_ENV')!='test'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $user = User::where(compact('phone'))->first();
        if(empty($user)) return responseFail('未查到有效用户或请先去注册！');
        else{
            $user->token = createNewToken($user->id);
            return responseSuccess($user->toArray());
        }

    }

    public function forgetPassword(Request $request) {

        $phone = $request->input('phone');
        $verify_code = $request->input('verify_code');
        $password = $request->input('password');

        $user = User::where(compact('phone'))->first();
        if(empty($user)) return responseFail('用户无效!');

        $this->validate($request, [
            'phone'=>'required|regex:/^1[3456789]\d{9}$/',
            'verify_code'=>'required|integer',
            'password'=>'required|confirmed|between:8,16|regex:/^(?![A-Z]+$)(?![a-z]+$)(?!\d+$)(?![\W_]+$)\S+$/',
        ]);

        if(env('APP_ENV')!='test'){
            $key = "verifyCode:$phone:$verify_code";
            if(Redis::exists($key)!=1){
                return responseFail('验证码错误！');
            }
        }

        $user->password = md5($password);
        $user->save();
        return responseSuccess();
    }

}
